package com.lsf.base_android.utils;

import android.os.Handler;
import android.os.Looper;

import com.lsf.base_android.base.BaseActivity;
import com.lsf.base_android.setting.Constants;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.FormEncodingBuilder;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * okhttp工具类
 * Created by lsf on 2016/1/25.
 */
public class OkHttpUtil {
    public static OkHttpClient mOkHttpClient;
    private static OkHttpUtil mInstance;
    private Handler mDelivery;
    /**
     * 请求时间
     */
    private static int TIMES = 30;

    public OkHttpUtil() {
        mOkHttpClient = new OkHttpClient();
        // 获取UI主线程
        mDelivery = new Handler(Looper.getMainLooper());
    }

    public static OkHttpUtil getInstance() {
        if (mInstance == null) {
            synchronized (OkHttpUtil.class) {
                if (mInstance == null) {
                    mInstance = new OkHttpUtil();
                }
            }
        }
        return mInstance;
    }

    /**
     * @param map
     * @return
     */
    private RequestBody mapToParam(HashMap<String, String> map) {
        // TODO Auto-generated method stub

        FormEncodingBuilder builder = new FormEncodingBuilder();
        for (Map.Entry<String, String> entry : map.entrySet()) {
            builder.add(entry.getKey(), entry.getValue());
        }
        return builder.build();
    }

    /**
     * 异步的get请求
     *
     * @param url
     * @param callback
     */
    public OkHttpUtil getOkHttp(String url, final int code,
                                HashMap<String, String> map, BaseActivity callback) {
        Request.Builder mBuilder = new Request.Builder();
        mBuilder.addHeader("apikey", "97e8d621474eea52233fd6a9f2b8727b");
        deliveryResult(callback, code, mBuilder
                .url(Constants.FORAMIL_WebName + url).post(mapToParam(map)).tag(callback.getLocalClassName()).build());
        return this;
    }

    public OkStartListener okStartListener;
    public OkSuccessListener okSuccessListener;
    public OkFailureListener okFailureListener;

    /**
     * 请求开始
     *
     * @param OkStart
     * @return
     */
    public OkHttpUtil setOnStartListener(OkStartListener OkStart) {
        this.okStartListener = OkStart;
        return this;
    }

    /**
     * 请求成功
     *
     * @param okSuccess
     * @return
     */
    public OkHttpUtil setOnSuccessListener(OkSuccessListener okSuccess) {
        this.okSuccessListener = okSuccess;
        return this;
    }

    /**
     * 请求失败
     *
     * @param okFailure
     * @return
     */
    public OkHttpUtil setOnFailureListener(OkFailureListener okFailure) {
        this.okFailureListener = okFailure;
        return this;
    }


    /**
     * 网络请求
     *
     * @param callback
     * @param code
     * @param request
     */
    private void deliveryResult(final OkHttpCallback callback, final int code,
                                Request request) {
        SendStart(code, callback);
        mOkHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(final Request request, final IOException e) {
                SendFailure(code, callback);
            }

            @Override
            public void onResponse(final Response response) {
                String string;
                try {
                    string = response.body().string();
                    SendSuccess(code, string, callback);
                    System.out.println("response: " + response);
                    System.out.println("response.cacheResponse: "
                            + response.cacheResponse());
                    System.out.println("response.networkResponse() "
                            + response.networkResponse());
                    ResetOption();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    SendFailure(code, callback);
                }

            }
        });
    }

    /**
     * 重置设置
     */
    public void ResetOption() {
        // TODO Auto-generated method stub
        /**
         * 超时重置
         */
        if (mOkHttpClient.getConnectTimeout() == TIMES) {
        } else {
            mOkHttpClient.setConnectTimeout(TIMES, TimeUnit.SECONDS);
        }

		/*	*//**
         * 缓存重置
         */
        /*
         * try { mOkHttpClient.getCache().getSize();
		 * mOkHttpClient.setCache(null); } catch (Exception e) { // TODO: handle
		 * exception }
		 */

    }

    /**
     * 开始
     *
     * @param code
     * @param callback
     */
    public void SendStart(final int code, final OkHttpCallback callback) {
        // TODO Auto-generated method stub
        mDelivery.post(new Runnable() {

            @Override
            public void run() {
                // TODO Auto-generated method stub
                if (okStartListener != null) {
                    okStartListener.onStart(code);
                }
                callback.onStart(code);
            }
        });
    }

    /**
     * 成功
     *
     * @param code
     * @param callback
     */
    public void SendSuccess(final int code, final String result,
                            final OkHttpCallback callback) {
        // TODO Auto-generated method stub
        mDelivery.post(new Runnable() {

            @Override
            public void run() {
                // TODO Auto-generated method stub
                if (okSuccessListener != null) {
                    okSuccessListener.onSuccess(result, code);
                }
                callback.onSuccess(result, code);
            }
        });
    }

    /**
     * 结束
     *
     * @param code
     * @param callback
     */
    public void SendFailure(final int code, final OkHttpCallback callback) {
        // TODO Auto-generated method stub
        mDelivery.post(new Runnable() {

            @Override
            public void run() {
                // TODO Auto-generated method stub
                if (okFailureListener != null) {
                    okFailureListener.onFailure(code);
                }
                callback.onFailure(code);
            }
        });
    }

    public interface OkHttpCallback {

        /**
         * @param result 回调参数
         * @param code   回调标记位
         */
        abstract void onSuccess(String result, int code);

        /**
         * @param code 回调标记位
         */
        abstract void onStart(int code);

        /**
         * @param code 回调标记位
         */
        abstract void onFailure(int code);

    }

    public interface OkSuccessListener {

        /**
         * @param result 回调参数
         * @param code   回调标记位
         */
        abstract void onSuccess(String result, int code);

    }

    public interface OkStartListener {

        /**
         * @param code 回调标记位
         */
        abstract void onStart(int code);

    }

    public interface OkFailureListener {

        /**
         * @param code 回调标记位
         */
        abstract void onFailure(int code);

    }
}
